package tools.event;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

public class Observer<T> {

    private static Executor executor;
    private final List<Listener<T>> listeners = new ArrayList<>();
    private Persistence<T> persistence;

    protected Observer() {
    }

    protected void addListener(Listener<T> listener) {
        listeners.add(listener);
    }

    protected boolean observe(T target) {
        boolean persistence = persistence(target);

        if (persistence) {
            listeners.forEach(item -> executor.execute(() -> item.action(target)));
        }

        return persistence;
    }

    private boolean persistence(T target) {
        if (persistence == null) {
            return true;
        } else {
            return persistence.save(target);
        }
    }

    protected void setPersistence(Persistence<T> persistence) {
        this.persistence = persistence;
    }

    public static void setExecutor(Executor executor) {
        Observer.executor = executor;
    }
}
